//

//  WatermarkContentView.swift

//  WatermarkCamera

//

//  Created by AxcLogo on 4/7/2024.

//

import Foundation
import AxcBedrock

// MARK: - [WatermarkContentView.MarginsCalibration]

extension WatermarkContentView {
    enum MarginsCalibration {
        case top, left, bottom, right
    }
}

// MARK: - [WatermarkContentView]

@objc

class WatermarkContentView: BaseView {
    // Open

    // 水印布局完成回调

    var layoutWatermarksBlock: AxcBlock.Empty?

    // Internal

    // 水印视图

    var watermarkView: BaseWatermarkTemplateView?

    // 水印模型

    var watermarkModel: WatermarkDetailModel?

    // 水印视图开始布局的回调

    var watermarkLayoutBlock: AxcBlock.OneParam<[UIView]>?

    // 水印视图移动的回调

    var watermarkMoveBlock: AxcBlock.OneParam<BaseWatermarkTemplateView>?

    // 水印视图点击的回调

    var watermarkActionBlock: AxcBlock.OneParam<UIView>?

    // 水印大边距校准

    var watermarkBigMarginsCalibration: [MarginsCalibration] = [.right, .bottom, .left, .top]

    // 水印小边距校准

    var watermarkSmallMarginsCalibration: [MarginsCalibration] = [.right, .top, .left, .bottom]

    // 可被触发的视图

    var hitsViews: [UIView] = []

    // 正常点位

    var portraitPoint: CGPoint?

    // 反向点位

    var portraitUpsideDownPoint: CGPoint?

    // 左侧点位

    var landscapeLeftPoint: CGPoint?

    // 右侧点位

    var landscapeRightPoint: CGPoint?

    // 拖动边距

    var panEdges: UIEdgeInsets = .Axc.Create(all: 2)

    // 全屏水印

    var fullScreenViews: [UIView] = []

    // 锁定正向

    var isLockPortrait: Bool = false

    // 是否一直锁定反转大小来约束范围，默认反转

    var isLockReverse: Bool = true

    // 是否允许水印拖动

    var isWatermarkMoveBlock: AxcBlock.Return<Bool> = { return true }

    // 二级仿射变换

    var secondaryTransform: CGAffineTransform? {
        didSet { updateWatermark() }
    }

    override func config() {
        backgroundColor = .clear
    }

    override func createUI() { }

    // 更新水印

    func updateWatermark() {
        guard let watermarkModel = watermarkModel else { return }

        setWatermark(model: watermarkModel)
    }

    // 更新水印

    func reloadWatermark() {
        guard let watermarkModel = watermarkModel else { return }

        watermarkView?.removeFromSuperview()

        watermarkView = nil

        setWatermark(model: watermarkModel)
    }

    // 设置水印

    func setWatermark(model: WatermarkDetailModel?) {
        DispatchQueue.main.async { [weak self] in

            guard let self = self else { return }

            guard let model else {
                self.watermarkModel = model

                self.watermarkView?.removeFromSuperview()

                self.watermarkView = nil

                return
            }

            if model.name != self.watermarkModel?.name { // 模版变化，重新创建
                self.watermarkModel = model

                self.watermarkView?.removeFromSuperview()

                self.watermarkView = nil

                var templateView: BaseWatermarkTemplateView?

                switch model.type {
                case .project: templateView = ProjectWatermarkView()

                case .clocking: templateView = ClockingWatermarkView()

                case .timeAddress: templateView = TimeAddressWatermarkView()

                case .security: templateView = SecurityWatermarkView()

                case .sanitation: templateView = SanitationWatermarkView()

                default: break
                }

                self.watermarkView = templateView
            }

            guard let templateView = self.watermarkView else { return }

            // 清空边距

            templateView.edgeCompensateDistance = .zero

            templateView.reloadUI(model)

            // 添加水印视图

            self.addSubview(templateView)

            // 设置水印视图的各项属性

            self.setttingWatermarkView()

            // 设置二级缩放 主要用于水印二次编辑

            if let secondaryTransform = self.secondaryTransform {
                templateView.transform = templateView.transform.concatenating(secondaryTransform)
            }
        }
    }

    func setttingWatermarkView() {
        guard let watermarkView = watermarkView else { return }

        // 添加和约束

        watermarkView.snp.makeConstraints { make in

            make.left.equalTo(panEdges.left)

            make.bottom.equalTo(-panEdges.bottom)

            if let defaultWidth = watermarkView.defaultWidth {
                make.width.equalTo(defaultWidth)
            }

//            make.height.equalTo(100)
        }

        // 拖动手势

        let pan = UIPanGestureRecognizer.Axc.Create { [weak self] pan in

            guard let weakSelf = self else { return }

            guard let watermarkView = weakSelf.watermarkView else { return }

            weakSelf.moveWatermarkView(pan)

            // 回调

            weakSelf.watermarkMoveBlock?(watermarkView)
        }

        watermarkView.addGestureRecognizer(pan)

        // 点击手势

        let tap = UITapGestureRecognizer.Axc.Create { [weak self] _ in

            guard let weakSelf = self else { return }

            guard let watermarkView = weakSelf.watermarkView else { return }

            weakSelf.watermarkActionBlock?(watermarkView)
        }

        watermarkView.addGestureRecognizer(tap)
    }

    // 移动水印

    func moveWatermarkView(_ pan: UIPanGestureRecognizer) {
        guard isWatermarkMoveBlock() else { return }

        guard let watermarkView = watermarkView,

              watermarkView.frame.size != .zero,

              let panView = pan.view else { return }

        let translation = pan.translation(in: watermarkView)

        let center = CGPoint(x: panView.center.x + translation.x,

                             y: panView.center.y + translation.y)

        moveWatermarkView(center)

        pan.setTranslation(CGPoint.zero, in: watermarkView) // 归零
    }

    // 移动水印

    func moveWatermarkView(_ center: CGPoint) {
        guard let watermarkView = watermarkView,

              watermarkView.frame.size != .zero else { return }

        let halfHeight = watermarkView.frame.height / 2

        let halfWidth = watermarkView.frame.width / 2

        // 判断边距

        var centerY = center.y

        var centerX = center.x

        // 与横竖屏有关

        var selfHeight = frame.size.height

        var selfWidth = frame.size.width

        if isLockReverse { // 锁定反转
            switch MotionTool.shared.orientation.value {
            case .landscapeRight,

                 .landscapeLeft:

                selfHeight = frame.size.width

                selfWidth = frame.size.height

            default: break
            }
        }

        // 边界补偿

        let edgeCompensateDistance = watermarkView.edgeCompensateDistance

        // 开始计算 有运算顺序要求

        let bottom = centerY + halfHeight + edgeCompensateDistance.bottom

        if bottom > (selfHeight - panEdges.bottom) { // 底部
            centerY = selfHeight - (panEdges.bottom + halfHeight + edgeCompensateDistance.bottom)
        }

        let top = centerY - (halfHeight + edgeCompensateDistance.top)

        if top < panEdges.top { // 顶部
            centerY = panEdges.top + halfHeight + edgeCompensateDistance.top
        }

        let right = centerX + halfWidth + edgeCompensateDistance.right

        if right > (selfWidth - panEdges.right) { // 右侧
            centerX = selfWidth - (panEdges.right + halfWidth + edgeCompensateDistance.right)
        }

        let left = centerX - (halfWidth + edgeCompensateDistance.left)

        if left < panEdges.left { // 左侧
            centerX = panEdges.left + halfWidth + edgeCompensateDistance.left
        }

        watermarkView.center = CGPoint(x: centerX, y: centerY)

        // 记录点位

        switch MotionTool.shared.orientation.value {
        case .portrait: portraitPoint = watermarkView.center

        case .landscapeLeft: landscapeLeftPoint = watermarkView.center

        case .portraitUpsideDown: portraitUpsideDownPoint = watermarkView.center

        case .landscapeRight: landscapeRightPoint = watermarkView.center

        default: break
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        guard let watermarkView = watermarkView else { return }

        if isLockPortrait {
            if let portraitPoint = portraitPoint {
                watermarkView.center = portraitPoint
            }

        } else {
            // 显示上一次拖动的坐标

            switch MotionTool.shared.orientation.value {
            case .portrait:

                if let portraitPoint = portraitPoint {
                    watermarkView.center = portraitPoint
                }

            case .landscapeLeft:

                if let landscapeLeftPoint = landscapeLeftPoint {
                    watermarkView.center = landscapeLeftPoint
                }

            case .portraitUpsideDown:

                if let portraitUpsideDownPoint = portraitUpsideDownPoint {
                    watermarkView.center = portraitUpsideDownPoint
                }

            case .landscapeRight:

                if let landscapeRightPoint = landscapeRightPoint {
                    watermarkView.center = landscapeRightPoint
                }

            default: break
            }
        }

        // 预览区域高度大小与纵横平有关

        var previewHeight = frame.size.height

        var previewWidth = frame.size.width

        if isLockReverse { // 是否反转
            if isLockPortrait { // 锁正向
            } else {
                switch MotionTool.shared.orientation.value {
                case .landscapeLeft,

                     .landscapeRight:

                    previewHeight = frame.size.width

                    previewWidth = frame.size.height

                default: break
                }
            }
        }

        // 校准水印位置，防止出界

        // 校准顶部

        func calibrationTop() {
            let topRect = panEdges.top + watermarkHalfSize.height + edgeCompensateDistance.top

            if watermarkView.center.y < topRect {
                watermarkView.center = CGPoint(x: watermarkView.center.x, y: topRect)
            }
        }

        // 校准左侧

        func calibrationLeft() {
            let leftRect = panEdges.left + watermarkHalfSize.width + edgeCompensateDistance.left

            if watermarkView.center.x < leftRect {
                watermarkView.center = CGPoint(x: leftRect, y: watermarkView.center.y)
            }
        }

        // 校准底部

        func calibrationBottom() {
            let bottomRect = previewHeight - (panEdges.bottom + watermarkHalfSize.height + edgeCompensateDistance.bottom)

            if watermarkView.center.y > bottomRect {
                watermarkView.center = CGPoint(x: watermarkView.center.x, y: bottomRect)
            }
        }

        // 校准右侧

        func calibrationRight() {
            let rightRect = previewWidth - (panEdges.right + watermarkHalfSize.width + edgeCompensateDistance.right)

            if watermarkView.center.x > rightRect {
                watermarkView.center = CGPoint(x: rightRect, y: watermarkView.center.y)
            }
        }

        let watermarkSize = CGSize(width: watermarkView.frame.width,

                                   height: watermarkView.frame.height)

        let watermarkHalfSize = CGSize(width: watermarkSize.width / 2, height: watermarkSize.height / 2)

        // 边界补偿

        let edgeCompensateDistance = watermarkView.edgeCompensateDistance

        if watermarkSize.height + watermarkView.edgeCompensateDistance.axc.vertical > previewHeight { // 水印比预览地方大
            // 进行校准，有运算顺序要求

            for cas in watermarkBigMarginsCalibration {
                switch cas {
                case .top: calibrationTop()

                case .left: calibrationLeft()

                case .bottom: calibrationBottom()

                case .right: calibrationRight()
                }
            }

        } else { // 水印比预览小
            //  有运算顺序要求

            for cas in watermarkSmallMarginsCalibration {
                switch cas {
                case .top: calibrationTop()

                case .left: calibrationLeft()

                case .bottom: calibrationBottom()

                case .right: calibrationRight()
                }
            }
        }

        // 需要触碰的水印进行回调

        // 使控制视图点击事件何其不冲突

        // 水印视图

        hitsViews.removeAll()

        hitsViews.append(watermarkView)

        watermarkLayoutBlock?(hitsViews)

        layoutWatermarksBlock?()
    }

    // 设置视图阴影

    func setShadow(_ view: UIView, color: UIColor = "606066".axc.uiColor) {
        view.layer.shadowColor = color.cgColor

        view.layer.shadowRadius = 4

        view.layer.shadowOffset = CGSize(width: 0, height: 1)

        view.layer.shadowOpacity = 0.8
    }
}
